<template>
  <div class="app-container">
    <el-form ref="queryFormRef" :model="page.queryForm" inline>
      <el-form-item label="字典名称" prop="dictTypename">
        <el-input
          v-model="page.queryForm.dictTypename"
          placeholder="请输入字典名称"
          clearable
          @keyup.enter="getDictTypeList"
        />
      </el-form-item>

      <el-form-item label="字典类型" prop="dict_type">
        <el-input
          v-model="page.queryForm.dict_type"
          placeholder="请输入字典类型"
          clearable
          @keyup.enter="getDictTypeList"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="page.queryForm.status" style="width: 140px">
          <el-option label="正常" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>

      <el-form-item label="创建时间" prop="create_time">
        <el-date-picker
          v-model="daterange"
          type="daterange"
          format="YYYY-MM-DD"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleDateChange"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="getDictTypeList"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <vxe-toolbar
      ref="toolbarRef"
      custom
      print
      :refresh="{ query: getDictTypeList }"
    >
      <template #buttons>
        <el-button type="primary" icon="Plus" plain @click="handleAdd()"
          >新增</el-button
        >
        <el-button type="success" icon="Edit" plain @click="handleUpdate()"
          >修改</el-button
        >
        <el-popconfirm
          title="您确定要删除选中的数据吗?"
          confirm-button-text="确认"
          cancel-button-text="取消"
          @confirm="handleDelete()"
        >
          <template #reference>
            <el-button type="danger" icon="Delete" plain>删除</el-button>
          </template>
        </el-popconfirm>
        <el-button type="warning" icon="Download" plain @click="handleExport()"
          >导出</el-button
        >
      </template>
    </vxe-toolbar>

    <vxe-table
      ref="dictTypeTableRef"
      border="inner"
      align="center"
      :column-config="{ resizable: true }"
      :row-config="{ isHover: true }"
      :print-config="{}"
      :loading="loading"
      :data="tableData"
      @checkbox-all="selectAllChangeEvent"
      @checkbox-change="selectChangeEvent"
    >
      <vxe-column type="checkbox" width="60"></vxe-column>
      <vxe-column field="dict_id" title="字典类型ID" width="100"></vxe-column>
      <vxe-column field="dict_name" title="字典类型名称"></vxe-column>
      <vxe-column field="dict_type" title="字典类型">
        <template #default="{ row }">
          <router-link :to="{ path: '/system/dict-data/' + row.dict_id }" class="link-type">{{
            row.dict_type
          }}</router-link>
        </template>
      </vxe-column>
      <vxe-column title="状态">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            :active-value="0"
            :inactive-value="1"
            @change="handleStatusChange(row)"
          ></el-switch>
        </template>
      </vxe-column>
      <vxe-column field="remark" title="备注"></vxe-column>
      <vxe-column field="create_time" title="创建时间"></vxe-column>
      <vxe-column title="操作" min-width="100">
        <template #default="{ row }">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(row)"
            >修改</el-button
          >
          <el-popconfirm
            title="您确定要删除此数据吗?"
            confirm-button-text="确认"
            cancel-button-text="取消"
            @confirm="handleDelete(row)"
          >
            <template #reference>
              <el-button link type="primary" icon="Delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </vxe-column>
    </vxe-table>

    <el-row justify="end" style="padding: 16px">
      <el-pagination
        v-show="page.total > 0"
        v-model:current-page="page.queryForm.pageNum"
        v-model:page-size="page.queryForm.pageSize"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @size-change="getDictTypeList"
        @current-change="getDictTypeList"
      />
    </el-row>

    <!-- 新增、修改对话框的显示与隐藏 -->
    <el-dialog
      v-model="open"
      :title="title"
      width="700px"
      append-to-body
      destroy-on-close
      @closed="reset"
    >
      <el-form
        ref="formRef"
        :model="page.form"
        :rules="page.rules"
        label-width="120px"
      >
        <el-form-item label="字典类型名称" prop="dict_name">
          <el-input
            v-model="page.form.dict_name"
            placeholder="请输入字典类型名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="字典类型" prop="dict_type">
          <el-input
            v-model="page.form.dict_type"
            placeholder="请输入字典类型"
            clearable
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="page.form.status">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="page.form.remark"
            type="textarea"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submit">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from "vue";
import {
  dictTypeList,
  dictTypeAdd,
  dictTypeEdit,
  dictTypeDel,
  dictTypeInfo,
  dictTypeExport,
} from "@/api/system/dict.ts";
import { downloadFile } from "@/utils/download.ts";

const queryFormRef = ref(null);
const daterange = ref([]);
const toolbarRef = ref(null);
const dictTypeTableRef = ref(null);
const formRef = ref();

const page = reactive({
  // 查询表单
  queryForm: {
    dict_id: null,
    dictTypename: null,
    dict_type: null,
    status: null,
    begin_time: null,
    end_time: null,
    pageNum: 1,
    pageSize: 10,
  },
  total: 0,
  // 新增、修改表单
  form: {},
  // 新增、修改表单验证规则
  rules: {
    dict_name: [
      { required: true, message: "字典类型名称不能为空", trigger: "blur" },
    ],
    dict_type: [
      { required: true, message: "字典类型不能为空", trigger: "blur" },
    ],
  },
});

// 表格数据
const tableData = ref([]);
// 选中的表格ID
const checkedIds = ref([]);
// 加载状态
const loading = ref(false);
// 新增、修改对话框的显示与隐藏
const open = ref(false);
// 对话框标题
const title = ref("");


nextTick(() => {
  // 将表格和工具栏进行关联
  const $table = dictTypeTableRef.value;
  const $toolbar = toolbarRef.value;
  if ($table && $toolbar) {
    $table.connect($toolbar);
  }
});

onMounted(() => {
  getDictTypeList();
  resetForm();
});

/**
 * 创建日期范围改变
 * @param {*} e
 */
function handleDateChange(e) {
  if (e) {
    page.queryForm.begin_time = e[0];
    page.queryForm.end_time = e[1];
  } else {
    page.queryForm.begin_time = null;
    page.queryForm.end_time = null;
  }
}

/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  daterange.value = [];
  page.queryForm.begin_time = null;
  page.queryForm.end_time = null;
  getDictTypeList();
}

/**
 * 表格全选事件
 * @param {*} e
 */
function selectAllChangeEvent(e) {
  checkedIds.value = e.records.map((item) => item.dict_id);
}

/**
 * 表格选中事件
 * @param {*} e
 */
function selectChangeEvent(e) {
  checkedIds.value = e.records.map((item) => item.dict_id);
}

/**
 * 新增字典类型
 */
function handleAdd() {
  open.value = true;
  title.value = "新增字典类型";
}

/**
 * 修改字典类型
 * @param {*} row
 */
function handleUpdate(row) {
  let ids = row ? [row.dict_id] : checkedIds.value;
  if (ids.length == 0) {
    return ElMessage.warning("请选择要修改的字典类型");
  } else if (ids.length > 1) {
    return ElMessage.warning("只能选择一个字典类型");
  }
  dictTypeInfo(ids[0]).then((res) => {
    open.value = true;
    title.value = "修改字典类型";
    // 文档说的是重置为初始值，当我们打开对话框时，我们已经赋值完毕了，所以使用resetFields会重置到赋完值的状态
    // 这里，我们借助nextTick去修改数据渲染页面：(不要忘记引用nextTick)
    nextTick(() => {
      page.form = {
        ...res.data,
        status: Number(res.data.status),
      };
    });
  });
}

/**
 * 删除字典类型
 * @param {*} row
 */
function handleDelete(row) {
  let ids = row ? [row.id] : checkedIds.value;
  if (ids.length == 0) {
    return ElMessage.warning("请选择要删除的字典类型");
  }
  dictTypeDel({ dictTypeIds: ids }).then((res) => {
    getDictTypeList();
  });
}

/**
 * 获取字典类型列表
 */
function getDictTypeList() {
  loading.value = true;
  dictTypeList(page.queryForm)
    .then((res) => {
      tableData.value = res.data.list;
      page.total = res.data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/**
 * 处理字典类型状态改变事件
 * @param {Object} row 行数据
 */
function handleStatusChange(row) {
  dictTypeEdit(row.id, { status: row.status }).then(() => {
    ElMessage.success("操作成功");
    getDictTypeList();
  });
}

/**
 * 提交新增、修改
 */
function submit() {
  formRef.value.validate((valid) => {
    if (valid) {
      if (page.form.dict_id) {
        dictTypeEdit(page.form.dict_id, {
          dictType: page.form,
        }).then(() => {
          open.value = false;
          ElMessage.success("操作成功");
          getDictTypeList();
        });
      } else {
        dictTypeAdd(page.form).then(() => {
          open.value = false;
          ElMessage.success("操作成功");
          getDictTypeList();
        });
      }
    }
  });
}

/**
 * 取消
 */
function cancel() {
  open.value = false;
}

/**
 * 重置
 */
function reset() {
  resetForm();
  page.roleIds = [];
}

/**
 * 重置表单
 */
function resetForm() {
  page.form = {
    id: null,
    dictTypename: null,
    nickname: null,
    email: null,
    phone: null,
    gender: 1,
    status: 0,
    dept_id: null,
    remark: null,
    password: null,
  };
}
</script>

<style lang="scss" scoped></style>
